import { Component, OnInit } from '@angular/core';
import { ApplicationService } from "../../../../../service/application.service";
import { BladeContainerBase } from "../../../../../shared/blade/blade-container-base";
import { Command } from "../../../../../shared/toolbar.service";
import { Blade } from "../../../../../shared/blade/blade.model";
import { BladeData } from "../../../../../shared/blade/blade-data";
import { DialogResult } from "../../../../../shared/dialog.service";
import { Observable } from "rxjs/Observable";


import { PermissionService } from "../../../../../service/permission.service";
import { RolePermissionEditComponent } from "../role-permission-edit/role-permission-edit.component";
import { RolePermissionService } from "../../../../../service/role-permission.service";
import { RolePermission } from "../../../../../entity/role-permission.model";

import { Permission } from "../../../../../entity/permission.model";
import { MenuShortcutListComponent } from "../../menu-shortcut/menu-shortcut-list/menu-shortcut-list.component";
import { Role } from "../../../../../entity/role.model";


@Component({
  selector: 'app-role-permission-list',
  templateUrl: './role-permission-list.component.html',
  styleUrls: ['./role-permission-list.component.css']
})
export class RolePermissionListComponent extends BladeContainerBase<RolePermission>{

  permissions: Permission[] = [];
  rolePermissions: RolePermission[] = [];
  currentRolePermission: RolePermission;
  constructor(
    private application: ApplicationService,
    private permissionService: PermissionService,
    private rolePermissionService: RolePermissionService,
  ) {
    super();
  }

  ngOnInit() {
    this.commands = [
      new Command("edit", "分配", "fa fa-edit", "setofkey:update", blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command("delete", "删除", "fa fa-trash-o", "setofkey:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade))
    ];
    super.ngOnInit();
    // this.getData()
  }


  /**
   * 初始化数据
   * 
   * @returns {(any | Observable<any> | Promise<any>)} 
   * @memberof PermissionListComponent
   */

  initData(): any | Observable<any> | Promise<any> {

    let getPermissions = this.permissionService.getPermissions();
    let getpermissionsById = this.rolePermissionService.getPermissionsByroleID(this.parentEntity.currentEntity.roleId);
    Promise.all([getPermissions, getpermissionsById])
      .then(res => {
        if (res[0]) {
          this.permissions = [...res[0]];
        };
        if (res[1]) {
          this.rolePermissions = [...res[1]];
        };

        //设置用户权限
        this.rolePermissions.forEach(r => {
          this.permissions.forEach(p => {
            if (r.permissionId == p.permissionId) {
              r.permissionName = p.permissionName;
              r.permissionDesc = p.permissionDesc;
            }
          });
        });
        this.currentRolePermission = this.rolePermissions[0];
        if (this.parentEntity.isShowChild) {
          this.showMenuShortcutListBlade(this.parentEntity.currentEntity);
        }
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);

  }

  /**
   *显示固定菜单
   *
   * @param {Role} selectedRole
   * @memberof RolePermissionListComponent
   */
  showMenuShortcutListBlade(selectedRole: Role) {
    if (this.parentEntity.currentEntity != selectedRole
      || this.bladeService.findBlade("menuShortcutList") == undefined) {
      this.currentBlade.bladeService.closeChildrenBlade;
      let data: BladeData = new BladeData();
      data.id = "menuShortcutList";
      data.title = selectedRole.roleName;
      data.subtitle = '固定菜单';
      data.isClosingDisabled = false;
      // tslint:disable-next-line:max-line-length
      const permissionListBlade = this.bladeService.createBlade(MenuShortcutListComponent, data, false,
         this.currentRolePermission, selectedRole);
      this.bladeService.showBlade(permissionListBlade, this.currentBlade);
    }
  }


  /**
   * 编辑
   * 
   * @param {Blade} blend 
   * @memberof PermissionListComponent
   */
  exeEdit(blend: Blade): void {

    //if (this.currentRolePermission != undefined) {
    let data: BladeData = new BladeData();
    data.id = "rolePermissionEdit";
    data.title = this.parentEntity.currentEntity.roleName;
    data.subtitle = '分配权限';
    let editRoleBlade = this.bladeService.createBlade(RolePermissionEditComponent, data, false, this.currentRolePermission, this.parentEntity.currentEntity);
    this.currentBlade.bladeService.showBlade(editRoleBlade, this.currentBlade);
    //}
  }
  canExeEdit(blend?: Blade): boolean {
    return true;

    //return this.currentRolePermission != null;
  }

  //................................................
  exeDelete(blend: Blade): void {
    let selectedKeys = this.getSelected();
    if (selectedKeys.length > 0) {
      this.dialogService
        .showConfirmationDialog("确认删除", "是否要删除选中项？")
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;
            this.rolePermissionService.batchDelete(selectedKeys.map(o => o.id))
              .then(res => {
                if (res) {
                  let parentContainerInstance = this.parentBlade.parentBlade.bladeContainerInstance;
                  parentContainerInstance.refresh(res);
                  // this.refresh(undefined);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }

  }
  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;
  }


  onItemCheack(event: HTMLInputElement, key: RolePermission) {
    key.isChecked = event.checked;
  }


  /**
   * 全选
   * 
   * 
   */
  onAllCheack(event: HTMLInputElement) {
    if (this.rolePermissions.length > 0) {
      for (let i = 0; i < this.rolePermissions.length; i++) {
        this.rolePermissions[i].isChecked = event.checked;
      }
    }
  }
  /**
   * 获得选中项
   * 
   * @returns {Permission[]} 
   * @memberof PermissionListComponent
   */
  getSelected(): RolePermission[] {
    if (this.rolePermissions.length > 0) {
      let filter = this.rolePermissions.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }

  onSeletedChange(selectRolePermission: RolePermission) {
    this.currentRolePermission = selectRolePermission;
  }

}





// WEBPACK FOOTER //
// ./src/app/module/admin/role/role-permission/role-permission-list/role-permission-list.component.ts